package com.brother.template.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.brother.template.model.User;
import com.brother.template.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @Auther: xjw
 * @Date: 2018/10/10 17:07
 * @Description:
 */
public class ShiroRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    /**
     * 获取用户的角色和权限
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * 登录认证
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        /**
         * 获取输入的用户名和密码
         */
        String userName = (String) authenticationToken.getPrincipal();
        User user = userService.getOne(new QueryWrapper<User>().lambda().eq(User::getUsercode, userName));
        if (user == null) {
            throw new UnknownAccountException("用户名或密码错误!");
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getUserpwd(), getName());

        return info;
    }
}
